package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;

import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService Cartservice;

    /**
     * 查询当前用户的购物车
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> getlist(){
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,currentId);
        List<ShoppingCart> list = Cartservice.list(queryWrapper);

        return R.success(list);
    }
    /**
     * 向购物车当中添加菜品
     */

    @PostMapping("/add")
    public R<Boolean> add(@RequestBody ShoppingCart ShoppingCart){
         Boolean add = Cartservice.add(ShoppingCart);
        return R.success(add);
    }

    /**
     * 清空购物车
     */
    @DeleteMapping("/clean")
    public R<Boolean> clean(){
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,currentId);
        boolean remove = Cartservice.remove(queryWrapper);
        return R.success(remove);
    }

    @PostMapping("/sub")
    public R<Boolean> sub(@RequestBody ShoppingCart shoppingCart){
        boolean flag = false;
        //用户ID
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        //用户ID
        Long userid = BaseContext.getCurrentId();
        queryWrapper.eq(ShoppingCart::getUserId,userid).
                eq(shoppingCart.getDishId()!=null,ShoppingCart::getDishId,shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId()!=null,ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        ShoppingCart one = Cartservice.getOne(queryWrapper);
        if (one.getNumber()>1){
            one.setNumber(one.getNumber()-1);
            flag = Cartservice.updateById(one);
        }else if (one.getNumber()==1){
            Cartservice.removeById(one);
        }

        System.err.println(one);
        return R.success(flag);
    }
}
